import axios from 'axios'
import {
    Message
} from 'element-ui'
// import {
//     getToken
// } from '../utils/token.js'


const instance = axios.create({
    //baseURL: '', // api的base_url process.env.BASE_API
    timeout: 50000
})


// request interceptor
instance.interceptors.request.use(
    config => {
        //const token = getToken()
        // if (token) {
        //     config.headers['Authorization'] = token // 让每个请求携带token
        // }
        return config
    },
    error => {
        console.log(error) // for debug
        Promise.reject(error)
    }
)

// respone interceptor
instance.interceptors.response.use(
    response => {

        const resp = response.data


        const errCode = resp.code

        if (errCode !== undefined) {

            if (errCode === 200) {
                return resp;
            } else if (errCode === 10003) {
                Message({
                    message: resp.message,
                    type: 'error',
                    duration: 5 * 1000
                })
                location.reload() //可以根据情况刷新页面
                return Promise.reject(new Error(resp.message))
            } else {
                // Message({
                //     message: resp.message,
                //     type: 'error',
                //     duration: 5 * 1000
                // })
            }
            return resp.data;
        } else {

            return response
        }
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export const createAPI = (url, method, data) => {
    let config = {}
    if (method === 'get') {
        config.params = data
    } else {
        config.data = data //包一层{xx：token，xxx：data}
    }
    return instance({
        url,
        method,
        ...config
    })
}

export const createFormAPI = (url, method, data) => {
    let config = {}
    config.data = data
    config.headers = {
        'Cache-Control': 'no-cache',
        'Content-Type': 'application/json'
    }
    config.responseType = 'json'
    config.transformRequest = [
        function (data) {
            let ret = ''
            for (let it in data) {
                ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
        }
    ]
    return instance({
        url,
        method,
        ...config
    })
}
